/**
 * 
 */
package com.yangtao.prototype.system.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.yangtao.framework.constant.Option;
import com.yangtao.framework.hibernate.BaseDao;
import com.yangtao.framework.hibernate.Selector;
import com.yangtao.framework.util.StringHelper;
import com.yangtao.prototype.system.entity.DataAuthority;
import com.yangtao.prototype.system.entity.MenuTree;
import com.yangtao.prototype.system.entity.SysUser;

/**
 * @author Administrator
 * 
 */
@Repository
public class UserDAO extends BaseDao<SysUser> {

	/**
	 * 根据用户ID取出用户ID对应的菜单
	 * 
	 * @param userId
	 *            用户ID
	 * @return 用户对应的菜单列表
	 */
	public List<MenuTree> findUserMenu(String userId) {
		String basHql = "select distinct m from MenuTree m, UserRole ur,Authority a where a.resourceId = m.id and a.resourceType='MENU' and a.role = ur.role and ur.user.id=? ";
		StringBuilder hql = new StringBuilder();
		// 检索第一层menu
		hql.append(basHql);
		hql.append(" and m.level = 1 ");
		String orderBy = " order by m.dispOrder";
		List<MenuTree> topLevel = find(hql.toString() + orderBy, userId);
		// 加载第二层menu
		for (MenuTree mt : topLevel) {
			hql.setLength(0);
			hql.append(basHql);
			hql.append(" and m.level = 2 ");
			hql.append(" and m.parentMenu.id = ?");
			List<MenuTree> secondLevel = find(hql.toString() + orderBy, userId,
					mt.getId());
			// 加载第三层menu
			for (MenuTree st : secondLevel) {
				hql.setLength(0);
				hql.append(basHql);
				hql.append(" and m.level = 3 ");
				hql.append(" and m.parentMenu.id = ?");
				List<MenuTree> thirdLevel = find(hql.toString() + orderBy,
						userId, st.getId());
				st.setSubMenus(thirdLevel);
			}
			mt.setSubMenus(secondLevel);
		}
		Selector selector = new Selector();
		List<MenuTree> menus = new ArrayList<MenuTree>();
		selector.add(".subMenus.subMenus.subMenus");
		if (topLevel == null || topLevel.size() == 0) {
			topLevel = find("from MenuTree m where m.level = 1 " + orderBy);
			for (MenuTree mt : topLevel) {
				// getHibernateTemplate().initialize(mt.getSubMenus());
				// for (MenuTree st : mt.getSubMenus()) {
				// getHibernateTemplate().initialize(st.getSubMenus());
				// }
				menus.add(toVO(mt, selector));
			}
		}
		return menus;
	}
	
	/**
	 * 获取用户可分配的角色
	 * @param companyId
	 * @return
	 */
	public List<Option> findRoles(String companyId) {
		String hql = "select new com.yangtao.framework.constant.Option(r.id,r.roleName) from Role r where r.companyId =?";
		return find(hql, companyId);
	}

	/**
	 * 获取用户授权的功能菜单
	 * @param userId 用户Id
	 * @return 功能菜单树
	 */
	public List<MenuTree> findMenus(String userId) {
		String basHql = "select distinct m from MenuTree m, UserRole ur,FunctionAuthority fa where fa.menu = m and fa.role = ur.role and ur.user.id=? ";
		StringBuilder hql = new StringBuilder();
		//TODO 修改
		// 检索第一层menu
		hql.append(basHql);
		hql.append(" and m.level = 1 ");
		String orderBy = " order by m.dispOrder";
		List<MenuTree> topLevel = find(hql.toString() + orderBy, userId);
		List<MenuTree> menus = new ArrayList<MenuTree>();
		if (topLevel == null || topLevel.size() == 0) {
			topLevel = find("from MenuTree m where m.level = 1 " + orderBy);
		}
		Selector selector = new Selector();
		// 加载菜单的层次
		selector.add(".subMenus.subMenus.subMenus");
		for (MenuTree mt : topLevel) {
			menus.add(toVO(mt, selector));
		}
		return menus;
	}

	/**
	 * 取到用户的数据权限
	 * 
	 * @param user
	 *            用户
	 * @return 数据权限键值对
	 */
	public Map<String, List<String>> findUserDataAuth(String authKey,
			SysUser user) {
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		for (DataAuthority da : user.getDataAuth()) {
			if (map.get(da.getResourceType()) == null)
				map.put(da.getResourceType(), new ArrayList<String>());
			List<String> darr = map.get(da.getResourceType());
			darr.add(da.getResourceId());
		}
		return map;
	}

	// /**
	// * 查找从顶级开始向下的子级菜单
	// *
	// * @param userId
	// * 用户Id
	// * @param topId
	// * 顶级菜单Id
	// * @return
	// */
	// public List<MenuTree> findSubMenus(String userId, String topId) {
	// String basHql = "select distinct m from MenuTree m, UserRole ur,Authority
	// a where a.resourceId = m.id and a.resourceType='MENU' and a.role =
	// ur.role and ur.user.id=? ";
	// StringBuilder hql = new StringBuilder();
	// hql.append(basHql);
	// hql.append(" and m.parentMenu.id = ? ");
	// String orderBy = " order by m.dispOrder";
	// List<MenuTree> secondRoot = find(hql.toString() + orderBy, userId,
	// topId);
	// // 如果查不到，就不按照权限差，这个是权宜之计，以后要删除
	// List<MenuTree> menus = new ArrayList<MenuTree>();
	// Selector selector = new Selector();
	// // 加载菜单的层次
	// selector.add(".subMenus.subMenus");
	// if (secondRoot == null || secondRoot.size() == 0) {
	// secondRoot = find("from MenuTree m where m.parentMenu.id =?"
	// + orderBy, topId);
	// }
	// for (MenuTree mt : secondRoot) {
	// menus.add(toVO(mt, selector));
	// }
	// return menus;
	// }

	/**
	 * 查询用户已经分配的角色
	 * 
	 * @param userId
	 *            用户ID
	 * @return
	 */
	public List<Option> findDistributeRoles(String userId) {
		if (StringHelper.isEmpty(userId)) {
			// 已分配角色
			return null;
		} else {
			// 已分配角色
			String hql1 = "select new com.yangtao.framework.constant.Option(ur.role.id,ur.role.roleName) from UserRole ur where ur.user.id=?";
			return find(hql1, userId);
		}
	}

	public List<Option> findUnDistributeRoles(String userId) {
		if (StringHelper.isEmpty(userId)) {
			// 未分配角色
			String hql = "select new com.yangtao.framework.constant.Option(r.id,r.roleName) from Role r";
			return find(hql);
		} else {
			// 未分配角色
			String hql2 = "select new com.yangtao.framework.constant.Option(r.id,r.roleName) from Role r where r not in (select ur.role from UserRole ur where ur.user.id=?)";
			return find(hql2, userId);
		}
	}

	/**
	 * 删除用户的角色
	 * 
	 * @param userId
	 */
	public void deleteUserRoles(String userId) {
		batchExecute("delete from UserRole ur where ur.user.id=?", userId);
	}
}
